package com.rzjm.exercise.module.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.service.impl.BaseServiceImpl;
import com.rzjm.exercise.module.dao.DeviceRangeDao;
import com.rzjm.exercise.module.domain.DeviceRange;
import com.rzjm.exercise.module.service.DeviceRangeService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class DeviceRangeServiceImpl extends BaseServiceImpl<DeviceRangeDao, DeviceRange> implements DeviceRangeService {

    @Resource
    private DeviceRangeDao deviceRangeDao;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Override
    public DeviceRange getDeviceInfoByNum(String device_num) {
        QueryWrapper<DeviceRange> qw = new QueryWrapper<>();
        qw.eq("device_num",device_num);
        qw.last("limit 1");
        DeviceRange range = null;
        String key = "device_range_" + device_num;
        boolean blHasKey = redisTemplate.opsForHash().hasKey(key,key);
        if (blHasKey) {
            Object object = redisTemplate.opsForHash().get(key, key);
            String itemDicts = object != null ? object.toString() : "";
            if (StrUtil.isNotEmpty(itemDicts)) {
                JSONObject jsonObject = JSONUtil.parseObj(itemDicts);
                range = JSONUtil.toBean(JSONUtil.toJsonStr(jsonObject), DeviceRange.class);
            } else {
                range = deviceRangeDao.selectOne(qw);
                redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(range));
            }
        } else {
            range = deviceRangeDao.selectOne(qw);
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(range));
        }
        return range;
    }

    @Override
    public int resetDevice(DeviceRange device) {
        int ret = deviceRangeDao.updateById(device);
        if(ret > 0){
            QueryWrapper<DeviceRange> qw = new QueryWrapper<>();
            qw.eq("device_num",device.getDeviceNum());
            qw.last("limit 1");
            String key = "device_range_" + device.getDeviceNum();
            DeviceRange range = deviceRangeDao.selectOne(qw);
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(range));
        }
        return ret;
    }

    @Override
    public List<DeviceRange> getPageList(Page<DeviceRange> page, Map<String, Object> map) {
        return deviceRangeDao.getPageList(page, map);
    }
}
